package yoyosys;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.jetbrains.annotations.NotNull;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestMongoDb {
    private static Properties p = new Properties();

    public static void main(String[] args) throws InterruptedException, IOException {

        //读配置文件

        p.load( new FileInputStream( "conf.properties" ) );
        int threadNum = Integer.parseInt( p.getProperty( "threadNum" ) );
        int totalSendCount = Integer.parseInt( p.getProperty( "sendNumCount" ) );
        int sendCount = totalSendCount > 0 ? totalSendCount / threadNum : -1;
        int sleepTime = Integer.parseInt( p.getProperty( "sleepTime" ).toString() );

        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put( "sleepTime", sleepTime );
        paraMap.put( "sendCount", sendCount );
        paraMap.put( "conString", p.get( "conString" ).toString() );
        paraMap.put( "tableName", p.get( "tableName" ) );
        ExecutorService fixPool = Executors.newFixedThreadPool( threadNum );
        for (int i = 0; i < threadNum; i++) {
            Thread.sleep( 1 );

            fixPool.execute( () -> doTask( paraMap ) );
//            fixPool.execute(new Runnable() {
//                public void run() {
//                    doTask(sendCount);
//                }
//            });

        }
        fixPool.shutdown();

    }


    private static void doTask(Map<String, Object> paraMap) {
//        MongoClient mongoClient = MongoClients.create(
//                MongoClientSettings.builder()
//                        .applyToClusterSettings(builder ->
//                                builder.hosts(Arrays.asList(
//                                        new ServerAddress("172.16.150.86", 28017),
//                                        new ServerAddress("172.16.150.87", 28017),
//                                        new ServerAddress("172.16.150.88", 28017)
//                                )))
//                        .build());
        MongoClientURI connectionString = new MongoClientURI( paraMap.get( "conString" ).toString() );
        MongoClient mongoClient = new MongoClient( connectionString );
        MongoDatabase database = mongoClient.getDatabase( "test" );
        MongoCollection<Document> collection = database.getCollection( paraMap.get( "tableName" ).toString() );

        int sendCount = 0;
        System.out.println( "begin:" + Thread.currentThread().getName() );
        if (paraMap.get( "sendCount" ) != null) {
            sendCount = Integer.parseInt( paraMap.get( "sendCount" ).toString() );
        }
        String method = (String) p.get( "method" );

        while (true) {
            TestDoc testDoc = new TestDoc();

            try {
                if (sendCount > 0 || sendCount < 0) {
                    sendCount -= 1;

                    if ("query".equals( method )) {
                        doQuery( collection );
                    } else {
                        doInsert( collection, testDoc );
                    }


                    if (paraMap.get( "sleepTime" ) != null) {
                        Thread.sleep( Integer.parseInt( paraMap.get( "sleepTime" ).toString() ) );
                    }
                } else {
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        mongoClient.close();

    }

    private static void doInsert(@NotNull MongoCollection<Document> collection, @NotNull TestDoc testDoc) {
        //生成随机报文
        //insert
        collection.insertOne( testDoc.getDoc() );
    }

    private static void doQuery(@NotNull MongoCollection<Document> collection) {
        //select
        BasicDBObject queryDb = new BasicDBObject();
        queryDb.append( "eventType", "person235" );

        FindIterable<Document> iter = collection.find( new Document( "eventType", "personel manage" ).append( "eventSubtype", "safety helmet" ) ).limit( 10 );
//        System.out.println("find ok");

        MongoCursor<Document> cur = iter.iterator();
        while (cur.hasNext()) {
            cur.next();
        }

//        iter.forEach(new Block<Document>() {
//            public void apply(Document _doc) {
//                System.out.println(_doc.toJson());
//            }
//        });


    }


}
